<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/7/12
 * Time: 2:21 PM
 */
namespace app\backend\modules\theme\services;

use app\common\exceptions\BizException;
use app\common\models\Theme;
use app\common\services\AutoUpdate;
use app\common\helpers\Cache;
use app\backend\modules\theme\services\ThemeService;

class MarketService
{
    public function getList($search){
        $type = intval($search['type']);
        $category_id = intval($search['category_id']);
        $page = $search['page']?$search['page']:1;
        $limit = 30;
        $plugin_lists = $this->buildThemeList();
        $plugin_list = $plugin_lists['list'];
        foreach ($plugin_list as $key => $value) {
            $value['imageUrl'] = trim($value['imageUrl']);
            if (empty($value['imageUrl'])) {
                $plugin_list[$key]['imageUrl'] = '/static/images/no-img-default.png';
            }
        }
        $category_list = $plugin_lists['category_list'];
        if ($type) {
            foreach ($plugin_list as $k => $v) {
                if ($v['theme_type']!=$type) {
                    unset($plugin_list[$k]);
                }
            }
            $plugin_list = array_values($plugin_list);
        }
        if ($category_id) {
            foreach ($plugin_list as $k => $v) {
                if ($v['theme_category_id']!= $category_id) {
                    unset($plugin_list[$k]);
                }
            }
            $plugin_list = array_values($plugin_list);
        }
        $count = count($plugin_list);
        //分页
        $plugin_list = $this->page($plugin_list, $page, $limit, $count);
        $plugin_list = array_values($plugin_list);
        $data['data'] = $plugin_list;
        $data['category_list'] = $category_list;
        $data['current_page'] = $page;
        $data['per_page'] = $limit;
        $data['total'] = $count;
        $data['last_page'] = ceil($count / $limit);
        return $data;
    }

    /**
     * 获取本地模版
     * @param $search
     * @return mixed
     */
    public function getLocalList($search){
        $page = $search['page']?$search['page']:1;
        $limit = 30;
        $marketThemeLists = $this->buildThemeList();
        $marketThemeList = $marketThemeLists['list'];
        $marketThemeNames = [];
        foreach ($marketThemeList as $key => $value) {
            array_push($marketThemeNames,$value['theme']);
            $value['imageUrl'] = trim($value['imageUrl']);
            if (empty($value['imageUrl'])) {
                $marketThemeList[$key]['imageUrl'] = '/static/images/no-img-default.png';
            }
        }
        $themeList = [];
        $allLocals = (new ThemeService())->getLocalList();
        foreach ($allLocals as $v){
            if(!in_array($v['theme'],$marketThemeNames)){
                //排除模版市场上的模版
                /*if(!in_array(mb_substr($v['theme'],0,4),Theme::$localPre)){
                    throw new BizException($v['theme'].'模版名称不符合规范,请修改模版名称');
                }*/
                $v['type_desc'] = Theme::$typeDescMap[$v['type']];
                array_push($themeList,$v);
            }
        }
        $count = count($themeList);
        //分页
        $themeList = $this->page($themeList, $page, $limit, $count);
        $themeList = array_values($themeList);
        $data['data'] = $themeList;
        $data['current_page'] = $page;
        $data['per_page'] = $limit;
        $data['total'] = $count;
        $data['last_page'] = ceil($count / $limit);
        return $data;
    }
    /**
     * @return array
     */
    public function buildThemeList()
    {
        $installedThemeList = (new ThemeService())->getAll();
        $installedThemes = [];
        foreach ($installedThemeList as $v){
            array_push($installedThemes,$v['theme']);
        }
        $marketThemelist = $this->getMarketThemeList();
        array_multisort($marketThemelist['list'], SORT_DESC, $marketThemelist['list']);
        //所有
        $themeList = [];
        foreach ($marketThemelist['list'] as $v) {
            if(!in_array($v['name'],$installedThemes)){
                $tmp = [];
                $tmp['id'] = $v['id'];
                $tmp['name'] = $v['name'];
                $tmp['theme'] = $v['theme_name'];
                $tmp['theme_type'] = $v['theme_type'];
                $tmp['theme_category_id'] = $v['theme_category_id'];
                $tmp['type_desc'] = Theme::$typeDescMap[$v['theme_type']];
                $tmp['price'] = $v['price'];
                $tmp['thumb'] = $v['image'][0];
                array_push($themeList,$tmp);
            }
        }
        $res = [];
        $res['list'] = $themeList;
        $res['category_list'] = $marketThemelist['category_list'];
        return $res;
    }
    /**
     * 获取应用市场所有模版
     * @return mixed|null
     */
    public function getMarketThemeList() {
        $cacheKey = 'Theme::MarketService:themes-market-list';
        $res = Cache::get($cacheKey);
        if (!$res) {
            $domain = request()->getHttpHost();
            $res = (new AutoUpdate())->getAllThemes($domain);
            Cache::put($cacheKey,$res,60);
        }
        return $res['data'];
    }
    /**
     * 获取模版详情
     * @param $id
     * @param $domain
     * @return array
     */
    public function getDetail($id, $domain)
    {
        $cacheKey = 'Theme::MarketService:themes-market-detail:id:'.$id;
        $res = Cache::get($cacheKey);
        if (!$res) {
            $result = (new AutoUpdate())->getThemeDetail($id, $domain);
            $res = [];
            if ($result['result'] == '1') {
                $res = $result['data']['info'];
            }
            $res['imageUrl'] = trim($res['product_icon']);
            if (empty($res['imageUrl'])) {
                $res['imageUrl'] = '/static/images/no-img-default.png';
            }
            Cache::put($cacheKey,$res,60);
        }
        return $res;
    }
    /**
     * 分页（只在这里使用）
     * @param $list
     * @param $page
     * @param $limit
     * @param $count
     * @return array
     */
    private function page($list, $page, $limit, $count)
    {
        $start = ($page - 1) * $limit;
        $end = $page * $limit;

        if ($start > $count || $end > $count) {
            $start = floor($count / $limit) * $limit;
            $end = $count;
        }
        $new_list = [];
        for ($i = $start; $i < $end; $i++) {
            $new_list[$i] = $list[$i];
        }
        return $new_list;
    }
}